/*  header-comment
/*  file   : /Users/arida/react-hrm-h5/src/modules/identify/index
/*  author : arida
/*  date   : 2017-6-4 18:25:14
/*  last   : 2017-9-6 18:25:23
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { createForm } from "rc-form";
import autobind from "autobind-decorator";
import { Button, WhiteSpace, WingBlank, Flex } from "@ali/ding-ui";

// actions
import { fetchUser, saveUser, getFileKey } from "../../actions/identify/";
import { fetchDropDownOpthions } from "../../actions/steps/getUser";

// components
import Image from "../../components/Image";

// import AreaSelect from '../../components/AreaSelect';
import Upload from "../../components/Upload";
import Form from "./form";

// sample
import samplePic from "./sample.json";

// utils
import { merge } from "../../utils/common";
import { setTitle, toast, close,setRight } from "../../utils/dingtalk.js";
import { showMessage } from "../../utils/form.js";
import { set, remove } from "../../utils/db.js";

import "./index.less";

// 其实就是加密后的文件路径，后端可以通过解密fileKey，拿到文件的路径返回给前端
const fileKey = {};

//将store注入组件的props
const mapStateToProps = state => ({
  identify: state.IDENTIFY_CARD,
  options: state.STEPS_STEPTWO.options
});
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      fetchUser,
      fetchDropDownOpthions,
      getFileKey,
      saveUser
    },
    dispatch
  )
});

function goTo(hash) {
  window.location.hash = hash;
  // openLink(`#/${hash}`)
}
/**
 * 如果产品需要省市选择的话，把下面注释放到render对应位置
 *                            <AreaSelect
                                text="住址"
                                value={this.state.user.address || user.address}
                                data={citys}
                                onChange={this.onSelectChange.bind(this, 'address')}
                            />
 */

@connect(mapStateToProps, mapDispatchToProps)
class Identify extends Component {
  //constructor 非必需
  static defaultProps = {
    identify: {}
  };
  //propTypes 验证
  static propTypes = {
    form: PropTypes.shape({
      getFieldDecorator: PropTypes.func,
      getFieldsValue: PropTypes.func,
      getFieldProps: PropTypes.func
    }),
    identify: PropTypes.object.isRequired,
    options: PropTypes.object,
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      fetchUser: PropTypes.func.isRequired,
      fetchDropDownOpthions: PropTypes.func.isRequired,
      saveUser: PropTypes.func.isRequired,
      getFileKey: PropTypes.func.isRequired
    }).isRequired
  };
  constructor(props) {
    super(props);
    // state
    this.state = {
      samplePic,
      status: {
        front: false,
        back: false
      },
      pass: false,
      user: {}
    };
    remove("isUploadCard");
    setTitle({
      title: "身份证上传"
    });
  }
  componentWillMount() {
    this.props.actions.fetchDropDownOpthions();
  }

  // 拿着上传成功的fileKey（就是加密后的图片路径）去进行实名认证
  @autobind
  identifyCard() {
    this.props.actions
      .fetchUser({
        idside: [
          {
            type: "front",
            url: fileKey.front
          },
          {
            type: "back",
            url: fileKey.back
          }
        ]
      })
      .then(res => {
        // 后台验证通过则pass（显示下方信息编辑区域）
        if (res && res.success) {
          this.setState({
            pass: true
          });
        }
      });
  }
  @autobind
  handleFileChange(type, file) {
    const samplePic = this.state.samplePic;
    const status = this.state.status;
    const direction = this.state.direction;

    // 更新图片，更新成功状态
    const state = {
      ...this.state,
      samplePic: {
        ...samplePic,
        [type]: {
          [Math.floor(window.devicePixelRatio)]: file.url
        }
      },
      status: {
        ...status,
        [type]: true
      },
      direction: {
        ...direction,
        [type]: file.direction
      }
    };
    // upload
    this.props.actions.getFileKey(file.formData).then(res => {
      // 存起来文件对象
      fileKey[type] = res.result;
      this.setState(state);
      // 如果正反面全部上传成功，请求后台
      if (state.status.front && state.status.back) {
        this.identifyCard();
      }
    });
  }

  //通过jsapi返回
  @autobind
  handleFileChangeByTakePhoto(type, file, key) {
    const samplePic = this.state.samplePic;
    const status = this.state.status;
    // 更新图片，更新成功状态
    const state = {
      ...this.state,
      samplePic: {
        ...samplePic,
        [type]: {
          [Math.floor(window.devicePixelRatio)]: file.url
        }
      },
      status: {
        ...status,
        [type]: true
      }
    };

    fileKey[type] = key;
    this.setState(state);
    // 如果正反面全部上传成功，请求后台
    if (state.status.front && state.status.back) {
      this.identifyCard();
    }

  }

  @autobind
  saveUser() {
    this.props.form.validateFields(err => {
      if (!err) {
        this.props.actions
          .saveUser(
            merge(
              {
                ...this.props.identify.user,
                ...this.state.user
              },
              this.props.form.getFieldsValue()
            )
          )
          .then(res => {
            if (res.success) {
              toast({
                text: "提交成功",
                onSuccess() {
                  set("isUploadCard", "true");
                  //close();
                  //goTo("steps");
                  history.go(-1);
                }
              });
            }
          });
      } else {
        showMessage(err);
      }
    });
  }
  render() {
    // console.info(this.state)
    const { samplePic, status, direction = {} } = this.state;

    // 如果需要省市选择器的话，从props.identify中取出citys
    const { user = {} } = this.props.identify;
    const options = this.props.options || {};
    const { getFieldDecorator, getFieldProps } = this.props.form;

    return (
      <div className="identify-backgroud">
        <div className="scroll-body">
          <div className="indentify-bg">
            <div className="identify-inner">
              <WhiteSpace size="lg" />
              <p className="indentify-hint">上传身份证的正反面照片，注意反光，保证身份证内容清晰可见</p>
              <WingBlank>
                <div className="image-wrap">
                  <div className="image-list" style={{ position: "relative" }}>
                    <Upload
                      onFileChange={this.handleFileChange.bind(this, "front")}
                      handleFileChangeByTakePhoto={this.handleFileChangeByTakePhoto.bind(this, "front")}
                      type={1}
                    >
                      <Image
                        success={status.front}
                        src={
                          samplePic.front[Math.floor(window.devicePixelRatio)]
                        }
                        direction={direction.front}
                      />
                    </Upload>
                  </div>
                  <div className="image-list" style={{ position: "relative" }}>
                    <Upload
                      type={2}
                      handleFileChangeByTakePhoto={this.handleFileChangeByTakePhoto.bind(this, "back")}
                      onFileChange={this.handleFileChange.bind(this, "back")}
                    >
                      <Image
                        success={status.back}
                        src={
                          samplePic.back[Math.floor(window.devicePixelRatio)]
                        }
                        direction={direction.back}
                      />
                    </Upload>
                  </div>
                </div>
              </WingBlank>
              <div className="iden-txt">
                <Flex>
                  <Flex.Item>
                    <p className="identify-img-hint">身份证人像面</p>
                  </Flex.Item>
                  <Flex.Item>
                    <p className="identify-img-hint">身份证国徽面</p>
                  </Flex.Item>
                </Flex>
              </div>
              <div className="iden-button">
                <Flex>
                  <Flex.Item>
                    <WingBlank>
                      <div style={{ position: "relative" }}>
                        <Upload
                          handleFileChangeByTakePhoto={this.handleFileChangeByTakePhoto.bind(this, "front")}
                          type={1}
                          onFileChange={this.handleFileChange.bind(
                            this,
                            "front"
                          )}
                        >
                          <Button className="small-btn" type="primary">
                            拍照片
                          </Button>
                        </Upload>
                      </div>
                    </WingBlank>
                  </Flex.Item>
                  <Flex.Item>
                    <WingBlank>
                      <div style={{ position: "relative" }}>
                        <Upload
                          type={2}
                          handleFileChangeByTakePhoto={this.handleFileChangeByTakePhoto.bind(this, "back")}
                          onFileChange={this.handleFileChange.bind(
                            this,
                            "back"
                          )}
                        >
                          <Button className="small-btn" type="primary">
                            拍照片
                          </Button>
                        </Upload>
                      </div>
                    </WingBlank>
                  </Flex.Item>
                </Flex>
              </div>
            </div>
          </div>
          {this.state.pass && (
            <Form
              getFieldDecorator={getFieldDecorator}
              getFieldProps={getFieldProps}
              user={user}
              options={options}
            />
          )}
        </div>
        {this.state.pass && (
          <div className="scroll-btn identify-submit">
            <Button type="primary" onClick={this.saveUser}>
              确定
            </Button>
          </div>
        )}
      </div>
    );
  }
}
export default createForm()(Identify);
